-- cannon_improve
-- Created by chengb Jul/20/2015
-- 成就：排炮威力提升

-- 内部函数声明
local whenAttribBonus;

-- 注册玩家获得属性的回调
EventMgr.register("achievements/cannon_improve", event.BONUS_ATTRIB, function(args)
    whenAttribBonus(args);
end);

-- 注册玩家获得属性的回调
whenAttribBonus = function(args)
    local attrib = args.attrib;
    
    if attrib ~= "cannon" then
        return;
    end

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    local layer = DungeonM.currentLayer();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("cannon_improve");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end
        
        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            local improveValue = FormulaM.invoke("CALC_CANNON_ADDITION_DAMAGE");
            if improveValue < ruleArg["value"] then
                -- 提升的排炮威力未达标
                return false;
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local value   = ruleArg["value"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", value);

        return desc;
    end,
};